import React, { useEffect } from 'react';

function ajax(url) {
  return new Promise(function (resolve, reject) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.responseType = 'json';
    xhr.onload = function () {
      if (this.status === 200) {
        resolve(this.responseType);
      } else {
        reject(new Error(this.statusText));
      }
    };
    xhr.send();
  });
}

export default function PromiseDemo() {
  useEffect(() => {
    ajax('http://localhost:3001/api/ajax').then(
      function (res) {
        console.log(res);
      },
      function (error) {
        console.log(error);
      },
    );
  }, []);

  return (
    <div>
      <p>Promise 定义</p>
    </div>
  );
}
